#ifndef PROXY_ENCRY_SERVER_CONN_H_
#define PROXY_ENCRY_SERVER_CONN_H_

#include "proxy/encry/encrybase.h"
#include "proxy/http/reply.h"
#include "proxy/curl/curlconn.h"

namespace proxy{

  class EncryServerConn : public boost::noncopyable,
    public boost::enable_shared_from_this < EncryServerConn > {
  public:
    typedef boost::shared_ptr<EncryServerConn> Ptr;
    EncryServerConn(socket_ptr connect, CurlClientSession::Ptr curl_session);
    virtual ~EncryServerConn();
    void Start(std::string addr, uint16 port);
  private:
    void ReadMoreEncryData();
    void HandleReadEncryData(const boost::system::error_code& err, int size);
    void ProcessReadData(int size);

    void WriteEncryData(char*data, int size);
    void HandleWriteEncryData(const boost::system::error_code& err);


    //
    void HandleProxyConnect(const boost::system::error_code& err);
    void Respone503Error();
    void HandleClientWriteClose(boost::system::error_code err);
    void HandleServerWrite(boost::system::error_code err);
    void ReadServerData();
    void HandleReadServerData(const boost::system::error_code& err, int size);
  private:
    int AnalyzeHttpEncryKey(const char *buffer, int size);
  private:
    static const int MAX_BUFFER_SIZE = 8096;
    socket_ptr client_socket_;
    boost::asio::io_service &io_service_;
    boost::asio::ip::tcp::socket server_socket_;
    char client_buffer_[MAX_BUFFER_SIZE];
    char server_buffer_[MAX_BUFFER_SIZE];
    unsigned char key_;
    int header_size_;
    bool is_write_shake_;
    bool is_read_shake_;
    Reply reply_;
    CurlClientSession::Ptr curl_session_;
  };

}

#endif // PROXY_ENCRY_SERVER_CONN_H_